package com.aoxun.android.landlord.common;

import com.socks.library.KLog;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class RxSchedulers {
    /**
     * 现场调度
     * @param <T>
     * @return
     */
    public static <T>   ObservableTransformer<T, T> ioMain() {
        return new ObservableTransformer<T, T>() {
            @Override
            public Observable<T> apply(Observable<T> observable) {
                return observable
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

    /**
     * 校验响应码
     * @param <T>
     * @return
     */
    public static <T extends BaseResponseVo> ObservableTransformer<T,T> valedateCode() {
        return new ObservableTransformer<T,T>(){
            @Override
            public ObservableSource<T> apply(@NonNull Observable<T> upstream) {
                return upstream.flatMap(new Function<T, ObservableSource<T>>() {
                    @Override
                    public ObservableSource<T> apply(@NonNull final T responseVo) throws Exception {
                        if (responseVo.code != null && responseVo.code.equals("000000")) {
                            return Observable.just(responseVo);
                            /*
                            return Observable.create(new ObservableOnSubscribe<T>() {
                                @Override
                                public void subscribe(@NonNull ObservableEmitter<T> subscriber) throws Exception {
                                    try {
                                        subscriber.onNext(responseVo);
                                        subscriber.onComplete();
                                    } catch (Exception e) {
                                        subscriber.onError(e);
                                    }
                                }
                            });
                            */
                        }/* else if (result.isTokenInvalid()) {
                            //处理token失效，tokenInvalid方法在BaseActivity实现
                            //也可以用广播处理
                            tokenInvalid();
                        }*/ else {
                            KLog.e(""+responseVo);
                            return Observable.error(new MyException(responseVo.msg, responseVo.code));
                        }
                    }
                });
            }
        };
    }
}